var ACTION = require("../../base/action");
var utils = require("../../utils/utils");
var aTime = new ACTION("领时长", {});
var readArticle = require("../appCommon/readArticle");
var ad = {
  isOver: function () {
    return utils.existsTextStartsWith("领取成功");
  },
  watchAd(span) {
    var content = "秒后得";
    var UIText = utils.existsTextEndsWith(content);
    if (UIText) {
      this.watchAdType3();
      return;
    }
    var content = "跳过";
    var UIText = utils.existsTextEndsWith(content);
    if (UIText) {
      this.watchAdType2();
      return;
    }
    this.watchAdType1(span);
  },
  watchAdType2() {
    var span = utils.getRandom(45, 50);
    sleep(span * 1000);
    var content = "跳过";
    utils.clickTextEndsWith(content);
  },
  watchAdType3() {
    var span = utils.getRandom(32, 35);
    readArticle(span, 3);
    this.back();
  },
  watchAdType1(span) {
    var startTime = Date.now();
    var count = 0;
    while (true) {
      var hasWatch = (Date.now() - startTime) / 1000;
      if (hasWatch > span) {
        console.log("最长广告时间已达，强制结束");
        break;
      }
      sleep(2 * 1000);
      count++;
      if (count % 5 == 0) {
        console.log("广告已看：" + hasWatch, "/", span);
      }
      if (this.isOver()) {
        var interval = utils.getRandom(2, 4);
        console.log("广告已结束,再过-", interval, "-后关闭");
        sleep(interval * 1000);
        break;
      }
    }
    this.back();
  },
  back() {
    back();
  },
};

aTime.goStart = function () {
  var content = "免费领时长";
  var UIText = utils.clickTextStartsWith(content);
  if (UIText) {
    return true;
  }
  return false;
};
aTime.beforeExec = function () {
  sleep(utils.getRandom(2, 3, 1000));
  return true;
};
aTime.getType = function () {
  var content = "看视频领";
  var UIText = utils.clickTextStartsWith(content);
  if (UIText) {
    return 1;
  }
  var content = "秒后可继续领取";
  var UIText = utils.existsTextEndsWith(content);
  if (UIText) {
    return 2;
  }
  var content = "分钟后可继续领取";
  var UIText = utils.existsTextEndsWith(content);
  if (UIText) {
    return 3;
  }
};
aTime.exec = function () {
  console.show(true);
  for (var index = 0; index < 10; index++) {
    var type = this.getType();
    if (type == 3) {
      console.log("30分钟后可继续领取");
      return;
    }
    if (type == 2) {
      sleep(utils.getRandom(30, 35, 1000));
      index--;
      continue;
    }
    if (type == 1) {
      sleep(utils.getRandom(2, 3, 1000));
      ad.watchAd(60);
      sleep(utils.getRandom(2, 3, 1000));
    }
    if (!type) {
      console.log("领时长：意外的type", type);
      return;
    }
  }
  console.hide();
};

module.exports = aTime;
